using System.Collections.Generic;
using System.Threading;

namespace OracleInternal.Common
{
	internal class SQLLocalParsePrimaryKeyInfoPool
	{
		private object m_sync = new object();

		private long m_lastUsedCount;

		private Dictionary<string, SQLLocalParsePrimaryKeyInfo> m_cache;

		public int m_maxCacheSize;

		public SQLLocalParsePrimaryKeyInfoPool(int maxCacheSize)
		{
			m_maxCacheSize = maxCacheSize;
			m_cache = new Dictionary<string, SQLLocalParsePrimaryKeyInfo>(m_maxCacheSize);
		}

		private void RemoveLRU()
		{
			string text = null;
			long num = long.MaxValue;
			foreach (KeyValuePair<string, SQLLocalParsePrimaryKeyInfo> item in m_cache)
			{
				if (item.Value.m_lastUsedCount < num)
				{
					num = item.Value.m_lastUsedCount;
					text = item.Key;
				}
			}
			if (text != null)
			{
				m_cache[text].bIsPooled = false;
				m_cache.Remove(text);
			}
		}

		public void Put(string cmdText, SQLLocalParsePrimaryKeyInfo metaInfo)
		{
			if (metaInfo.bIsPooled)
			{
				return;
			}
			lock (m_sync)
			{
				if (m_cache.ContainsKey(cmdText))
				{
					SQLLocalParsePrimaryKeyInfo sQLLocalParsePrimaryKeyInfo = m_cache[cmdText];
					if (metaInfo.bPkFetched && !sQLLocalParsePrimaryKeyInfo.bPkFetched)
					{
						sQLLocalParsePrimaryKeyInfo.CopyPrimaryKeyInfoFrom(metaInfo);
						sQLLocalParsePrimaryKeyInfo.bPkFetched = true;
					}
					metaInfo = sQLLocalParsePrimaryKeyInfo;
				}
				else
				{
					if (m_cache.Count >= m_maxCacheSize)
					{
						RemoveLRU();
					}
					metaInfo.bIsPooled = true;
					metaInfo.m_lastUsedCount = ++m_lastUsedCount;
					m_cache.Add(cmdText, metaInfo);
				}
			}
		}

		public SQLLocalParsePrimaryKeyInfo Get(string cmdText)
		{
			SQLLocalParsePrimaryKeyInfo value = null;
			try
			{
				if (m_cache.TryGetValue(cmdText, out value))
				{
					value.m_lastUsedCount = Interlocked.Increment(ref m_lastUsedCount);
					return value;
				}
				return null;
			}
			catch
			{
				return null;
			}
		}
	}
}
